package com.gherasoft.view;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import com.gherasoft.adapter.MainAdapter;
import com.gherasoft.model.CheckListItem;
import com.gherasoft.model.CheckListModel;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * User: sckomoroh
 * Date: 3/12/13
 * Time: 10:23 PM
 */
public class MainActivity extends Activity
{
    private static MainAdapter adapter;

    public static CheckListModel getModel(int index)
    {
        return (CheckListModel)adapter.getItem(index);
    }

    public static int findModelIndex(Object model)
    {
        return adapter.getIndex(model);
    }

    public static void addModel(CheckListModel model)
    {
        adapter.addItem(model);
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ListView listView = (ListView)findViewById(R.id.allListView);
        ImageButton newListButton = (ImageButton)findViewById(R.id.createNewListButton);

        if (adapter == null)
        {
            adapter = new MainAdapter(this);
        }
        else
        {
            adapter.clear();
        }

        listView.setAdapter(adapter);

        listView.setOnItemLongClickListener(new ItemLongClickListener());
        listView.setOnItemClickListener(new ItemClickListener());
        newListButton.setOnClickListener(new NewListButtonListener());

        buildModel();
    }

    @Override
    public void onResume()
    {
        super.onResume();

        if (adapter != null)
        {
            adapter.update();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_option_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.import_list:
                importList();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void importList()
    {
        Intent intent = new Intent(MainActivity.this, OpenFileActivity.class);
        startActivity(intent);
    }

    private void buildModel()
    {
        String appDir = this.getApplicationInfo().dataDir;
        File dataDir = new File(appDir);

        if (!dataDir.exists())
        {
            dataDir.mkdir();
        }
        else
        {
            File[] listFiles = dataDir.listFiles();

            for(File listFile : listFiles)
            {
                try
                {
                    createModelFromFile(listFile);
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        }
    }

    private void createModelFromFile(File modelFile) throws Exception
    {
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(modelFile);
        Element rootElement = doc.getDocumentElement();
        if (rootElement.getTagName().equals("checkList") && rootElement.hasAttribute("name") && rootElement.hasAttribute("modified"))
        {
            String fileName = modelFile.getName();
            String listName = rootElement.getAttribute("name");
            String strModifiedDate = rootElement.getAttribute("modified");

            DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy kk:mm:ss");
            Date modifiedDdate = dateFormat.parse(strModifiedDate);

            CheckListModel model = new CheckListModel(fileName, listName, modifiedDdate);
            NodeList itemList = rootElement.getElementsByTagName("item");
            for (int i=0; i<itemList.getLength(); i++)
            {
                Node itemNode = itemList.item(i);
                Element itemElement = (Element)itemNode;

                if (itemElement.hasAttribute("name") && itemElement.hasAttribute("checked") && itemElement.hasAttribute("failed"))
                {
                    String itemName = itemElement.getAttribute("name");
                    String strChecked = itemElement.getAttribute("checked");
                    String strFailed = itemElement.getAttribute("failed");
                    boolean isChecked = Boolean.parseBoolean(strChecked);
                    boolean isFailed = Boolean.parseBoolean(strFailed);

                    model.addItem(new CheckListItem(itemName, isChecked, isFailed));
                }
            }

            adapter.addItem(model);
        }
    }

    private class ItemClickListener implements AdapterView.OnItemClickListener
    {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
        {
            Intent intent = new Intent(MainActivity.this, RunListActivity.class);
            intent.putExtra("model_index", i);
            startActivity(intent);
        }
    }

    private class NewListButtonListener implements View.OnClickListener
    {
        @Override
        public void onClick(View view)
        {
            Intent intent = new Intent(MainActivity.this, EditListActivity.class);
            startActivity(intent);
        }
    }

    private class ItemLongClickListener implements AdapterView.OnItemLongClickListener
    {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int index, long l)
        {
            AlertDialog dialog = createDialog(index);
            dialog.show();

            return false;
        }

        private AlertDialog createDialog(int index)
        {
            CheckListModel model = (CheckListModel)adapter.getItem(index);
            String dialogMessage = String.format(
                    "Do you want to remove '%s' list ?",
                    model.getListName());

            AlertDialog.Builder alt_bld = new AlertDialog.Builder(MainActivity.this);
            alt_bld.setMessage(dialogMessage)
                    .setCancelable(false)
                    .setPositiveButton("Yes", new RemoveDialogYesButtonListener(index))
                    .setNegativeButton("No", new RemoveDialogNoButtonListener());

            AlertDialog alert = alt_bld.create();
            alert.setTitle("Remove list");

            return alert;
        }
    }

    private class RemoveDialogYesButtonListener implements DialogInterface.OnClickListener
    {
        private int modelIndex;

        public RemoveDialogYesButtonListener(int modelIndex)
        {
            this.modelIndex = modelIndex;
        }

        @Override
        public void onClick(DialogInterface dialog, int id)
        {
            String fileName = ((CheckListModel)adapter.getItem(modelIndex)).getFileName();
            String fullFileName = String.format(
                    "%s/%s",
                    getApplicationInfo().dataDir,
                    fileName);

            File file = new File(fullFileName);
            file.delete();

            adapter.removeItem(modelIndex);
        }
    }

    private class RemoveDialogNoButtonListener implements DialogInterface.OnClickListener
    {
        @Override
        public void onClick(DialogInterface dialog, int id)
        {
            dialog.cancel();
        }
    }
}
